/**
 * 门店列表页面
 * 功能：展示附近门店列表，支持定位和筛选
 */

const app = getApp();
const apiService = require('../../../utils/api.js');

Page({
  data: {
    // 系统状态栏高度
    statusBarHeight: 44,
    
    // 位置信息
    location: {
      latitude: 0,
      longitude: 0,
      address: '定位中...'
    },
    
    // 门店列表
    storeList: [],
    isLoading: true,
    
    // 搜索关键词
    searchKeyword: '',
    
    // 筛选条件
    sortType: 'distance', // distance: 距离, rating: 评分, price: 价格
    filterDistance: 10, // 搜索半径(km)
    
    // 页面状态
    hasLocation: false,
    showLocationTip: false
  },

  onLoad(options) {
    console.log('门店列表页面加载', options);
    
    // 获取系统信息
    this.getSystemInfo();
    
    // 获取位置信息
    this.getLocation();
  },

  onShow() {
    console.log('门店列表页面显示');
  },

  /**
   * 获取系统信息
   */
  getSystemInfo() {
    const systemInfo = wx.getSystemInfoSync();
    this.setData({
      statusBarHeight: systemInfo.statusBarHeight || 44
    });
  },

  /**
   * 获取位置信息
   */
  async getLocation() {
    try {
      // 检查位置权限
      const authResult = await wx.getSetting();
      if (!authResult.authSetting['scope.userLocation']) {
        // 请求位置权限
        const authRes = await wx.authorize({
          scope: 'scope.userLocation'
        }).catch(() => ({ errMsg: 'authorize:fail' }));
        
        if (authRes.errMsg !== 'authorize:ok') {
          this.setData({
            showLocationTip: true,
            hasLocation: false
          });
          // 使用默认位置加载门店
          this.loadStoreList(39.9042, 116.4074); // 北京坐标
          return;
        }
      }
      
      // 获取当前位置
      const locationRes = await wx.getLocation({
        type: 'gcj02'
      });
      
      // 逆地理编码获取地址
      const address = await this.getAddressByLocation(locationRes.latitude, locationRes.longitude);
      
      this.setData({
        location: {
          latitude: locationRes.latitude,
          longitude: locationRes.longitude,
          address: address || '位置获取成功'
        },
        hasLocation: true,
        showLocationTip: false
      });
      
      // 加载门店列表
      this.loadStoreList(locationRes.latitude, locationRes.longitude);
      
    } catch (error) {
      console.error('获取位置失败:', error);
      this.setData({
        location: {
          latitude: 39.9042,
          longitude: 116.4074,
          address: '位置获取失败，使用默认位置'
        },
        hasLocation: false,
        showLocationTip: true
      });
      
      // 使用默认位置加载门店
      this.loadStoreList(39.9042, 116.4074);
    }
  },

  /**
   * 根据坐标获取地址
   */
  async getAddressByLocation(latitude, longitude) {
    try {
      // 这里应该调用地图API进行逆地理编码
      // 暂时返回模拟地址
      return `纬度:${latitude.toFixed(4)}, 经度:${longitude.toFixed(4)}`;
    } catch (error) {
      console.error('逆地理编码失败:', error);
      return null;
    }
  },

  /**
   * 加载门店列表
   */
  async loadStoreList(latitude, longitude) {
    try {
      this.setData({
        isLoading: true
      });
      
      const storeManager = app.getStoreManager();
      const storeList = await storeManager.getStoreList();
      
      if (storeList && storeList.length > 0) {
        // 处理门店数据
        const processedStoreList = storeList.map(store => ({
          id: store.storeId || store._id,
          name: store.name,
          address: store.address,
          phone: store.phone,
          image: store.images && store.images.length > 0 ? store.images[0] : '/assets/store/default_store.png',
          rating: store.rating || 4.5,
          distance: store.location ? this.calculateDistance(latitude, longitude, store.location.latitude, store.location.longitude) : 0,
          services: store.services || [],
          openTime: store.openingHours || '09:00-21:00',
          tags: store.tags || ['宠物美容', '宠物寄养'],
          latitude: store.location ? store.location.latitude : 0,
          longitude: store.location ? store.location.longitude : 0
        }));
        
        // 根据排序类型排序
        this.sortStoreList(processedStoreList);
        
        this.setData({
          storeList: processedStoreList,
          isLoading: false
        });
      } else {
        console.error('获取门店列表失败: 门店列表为空');
        this.setData({
          storeList: [],
          isLoading: false
        });
        
        wx.showToast({
          title: '暂无门店数据',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('加载门店列表异常:', error);
      this.setData({
        storeList: [],
        isLoading: false
      });
      
      wx.showToast({
        title: '网络异常，请重试',
        icon: 'none'
      });
    }
  },

  /**
   * 计算距离
   */
  calculateDistance(lat1, lng1, lat2, lng2) {
    const R = 6371; // 地球半径(km)
    const dLat = (lat2 - lat1) * Math.PI / 180;
    const dLng = (lng2 - lng1) * Math.PI / 180;
    const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
              Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
              Math.sin(dLng / 2) * Math.sin(dLng / 2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    const distance = R * c;
    
    if (distance < 1) {
      return `${Math.round(distance * 1000)}m`;
    } else {
      return `${distance.toFixed(1)}km`;
    }
  },

  /**
   * 门店列表排序
   */
  sortStoreList(storeList) {
    const { sortType } = this.data;
    
    storeList.sort((a, b) => {
      switch (sortType) {
        case 'distance':
          return parseFloat(a.distance) - parseFloat(b.distance);
        case 'rating':
          return b.rating - a.rating;
        case 'price':
          // 按服务最低价格排序
          const aMinPrice = Math.min(...(a.services.map(s => s.price) || [0]));
          const bMinPrice = Math.min(...(b.services.map(s => s.price) || [0]));
          return aMinPrice - bMinPrice;
        default:
          return 0;
      }
    });
  },

  /**
   * 返回上一页
   */
  onBack() {
    wx.navigateBack();
  },

  /**
   * 搜索输入
   */
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },

  /**
   * 执行搜索
   */
  onSearch() {
    const { searchKeyword, location } = this.data;
    if (searchKeyword.trim()) {
      // 重新加载门店列表（带搜索关键词）
      this.loadStoreList(location.latitude, location.longitude);
    }
  },

  /**
   * 清除搜索
   */
  onClearSearch() {
    this.setData({
      searchKeyword: ''
    });
    // 重新加载门店列表
    const { location } = this.data;
    this.loadStoreList(location.latitude, location.longitude);
  },

  /**
   * 切换排序方式
   */
  onSortChange(e) {
    const sortType = e.currentTarget.dataset.sort;
    this.setData({
      sortType: sortType
    });
    
    // 重新排序当前列表
    const storeList = [...this.data.storeList];
    this.sortStoreList(storeList);
    this.setData({
      storeList: storeList
    });
  },

  /**
   * 点击门店卡片
   */
  onStoreCardTap(e) {
    const storeId = e.currentTarget.dataset.storeId;
    console.log('点击门店:', storeId);
    
    // 跳转到门店详情页
    wx.navigateTo({
      url: `/pages/store/store-detail/index?storeId=${storeId}`
    });
  },

  /**
   * 拨打电话
   */
  onCallPhone(e) {
    e.stopPropagation();
    const phone = e.currentTarget.dataset.phone;
    
    wx.makePhoneCall({
      phoneNumber: phone
    }).catch(error => {
      console.error('拨打电话失败:', error);
    });
  },

  /**
   * 查看地图
   */
  onViewMap(e) {
    e.stopPropagation();
    const { latitude, longitude, name, address } = e.currentTarget.dataset;
    
    wx.openLocation({
      latitude: parseFloat(latitude),
      longitude: parseFloat(longitude),
      name: name,
      address: address
    }).catch(error => {
      console.error('打开地图失败:', error);
    });
  },

  /**
   * 重新定位
   */
  onRelocate() {
    this.setData({
      showLocationTip: false
    });
    this.getLocation();
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    const { location } = this.data;
    this.loadStoreList(location.latitude, location.longitude).finally(() => {
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 上拉加载更多
   */
  onReachBottom() {
    // 这里可以实现分页加载
    console.log('上拉加载更多');
  }
});